<!--
 * @Author: C.
 * @Date: 2023-04-28 13:42:12
-->
<template>
  <Tooltip placement="top">
    <template #title>
      <span>导出</span>
    </template>
    <ExportOutlined @click="openModal" />
    <!-- loading: { type: Boolean },
  loadingTip: { type: String }, -->
    <BasicModal
      v-model:visible="visibleRef"
      title="导出工作项"
      @ok="toExport(false)"
      width="55%"
      :loading="loading"
      loadingTip="正在导出,请稍等..."
    >
      <Divider orientation="left">文件名称</Divider>
      <Input v-model:value="defaultFilename" :addon-after="'.' + exportType" style="width: 350px" />
      <Divider orientation="left">数据来源</Divider>
      <RadioGroup v-model:value="exportSource">
        <Radio value="Current">当前页</Radio>
        <Radio value="Selected">已选</Radio>
        <Radio value="All">全量</Radio>
        <Radio value="Filtered">条件筛选</Radio>
      </RadioGroup>
      <Divider orientation="left">导出类型</Divider>
      <RadioGroup v-model:value="exportType">
        <Radio value="xlsx"
          >Excel
          <span class="cursor-pointer text-blue-600" @click="toExport(true)">
            (导出模板.xlsx)
          </span>
        </Radio>
        <Radio value="txt">TXT</Radio>
      </RadioGroup>
      <Divider orientation="left">导出字段</Divider>
      <div class="mb-2">
        <Checkbox
          v-model:checked="fieldState.checkAll"
          :indeterminate="fieldState.indeterminate"
          @change="onCheckAllChange"
        >
          Check all
        </Checkbox>
      </div>
      <CheckboxGroup v-model:value="fieldState.checkedList">
        <Row :gutter="[20, 15]">
          <Col span="4" v-for="item in columnOption" :key="(item.value as string)">
            <Checkbox :value="item.value"
              ><span class="text-base block min-w-30">{{ item.label }}</span></Checkbox
            >
          </Col>
        </Row>
      </CheckboxGroup>
      <!-- <div v-for="(item, index) in columnOption" :key="index">{{ index }}</div> -->
    </BasicModal>
  </Tooltip>
</template>
<script lang="ts" setup name="ExportSetting">
  // ----------------------------- 第三方引入 -----------------------------
  import { ref, reactive, watch, computed, watchEffect } from 'vue';
  import { ExportOutlined } from '@ant-design/icons-vue';
  import {
    Tooltip,
    Divider,
    RadioGroup,
    Radio,
    Checkbox,
    CheckboxGroup,
    CheckboxOptionType,
    Row,
    Col,
    Input,
  } from 'ant-design-vue';
  import type { BookType } from 'xlsx';

  // ----------------------------- hooks -----------------------------
  import { useTableContext } from '../../hooks/useTableContext';

  // ----------------------------- 组件 -----------------------------
  import { BasicModal } from '/@/components/Modal';

  // ----------------------------- 其他引入 -----------------------------
  import { export2file, IExportSourceType } from '/~/utils/file/exportHelp';
  import { dateUtil } from '/@/utils/dateUtil';
  import { isFunction } from '/@/utils/is';

  //----------------------------- 变量声明区 -----------------------------
  const visibleRef = ref<boolean>(false);
  const exportType = ref<BookType>('xlsx');
  const exportSource = ref<IExportSourceType>('Current');
  const loading = ref<boolean>(false);
  const defaultFilename = ref('');
  const fieldState = reactive<{
    indeterminate: boolean;
    checkAll: boolean;
    checkedList: string[];
    isInit: boolean;
  }>({
    indeterminate: true,
    checkAll: false,
    checkedList: [],
    isInit: false,
  });
  // ----------------------------- hooks使用区 -----------------------------
  const table = useTableContext();
  const columnOption = computed((): CheckboxOptionType[] => {
    return table.getColumns({ ignoreAction: true, ignoreIndex: true }).map((item) => {
      return {
        value: item.dataIndex as string,
        label: item.title as string,
      };
    });
  });
  // defaultHidden
  // ----------------------------- 钩子函数区 -----------------------------
  watch(
    () => fieldState.checkedList,
    (val) => {
      fieldState.indeterminate = !!val.length && val.length < columnOption.value.length;
      fieldState.checkAll = val.length === columnOption.value.length;
    },
  );
  watchEffect(() => {
    setTimeout(() => {
      const columns = table.getColumns();
      if (columns.length && !fieldState.isInit) {
        init();
      }
    }, 0);
  });
  //  ----------------------------- 自定义方法区 -----------------------------
  const onCheckAllChange = (e: any) => {
    Object.assign(fieldState, {
      checkedList: e.target.checked ? columnOption.value.map((item) => item.value) : [],
      indeterminate: false,
    });
  };
  function init() {
    const checkList = table
      .getColumns({ ignoreAction: true, ignoreIndex: true })
      .map((item) => {
        if (item.defaultHidden) {
          return '';
        }
        return item.dataIndex || item.title;
      })
      .filter(Boolean) as string[];

    defaultFilename.value = getTableName();

    fieldState.isInit = true;
    fieldState.checkedList = checkList;
  }
  function toExport(isTem = false) {
    loading.value = true;
    // dateUtil
    let title = getTableName();
    export2file({
      table,
      fields: fieldState.checkedList,
      type: exportType.value,
      filename: title,
      exportSource: exportSource.value,
      isTem,
      cb: () => {
        loading.value = false;
      },
    });
  }
  function getTableName(): string {
    let title = table.getProps.value?.title;
    if (isFunction(title)) {
      title = title({ rowCount: 0 });
    }
    !title && (title = 'Excel');
    title += `(${dateUtil().format('YYYYMMDDHHmm')})`;
    return title as string;
  }
  function openModal() {
    visibleRef.value = true;
  }
</script>
<style lang="less" scoped></style>
